<template>
  <div class="category-list">
    <div class="category-item" v-for="(items, index) in list" :key="index">
      <div :class="`category-item-col${i + 1}`" v-for="(it, i) in items" :key="i">
        <el-input v-model="it.title" :disabled="it.pid > 0" placeholder="请输入内容" />
      </div>
      <el-button v-if="items.length < 3" type="text" class="category-list__add" @click="add(items)">添加</el-button>
      <el-button v-if="items.length >= 1 && list.length > 1" type="text" class="category-list__add" @click="del(items)">删除</el-button>
    </div>
    <el-button type="text" style="width: 60px" @click="addItem">添加根项</el-button>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import baseService from "@/service/baseService";

export default defineComponent({
  name: "select-source",
  emits: ["update:modelValue"],
  props: {
    modelValue: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    onMounted(() => {});
    const methods = {
      async add(items) {
        const { title, id = 0 } = items.slice().pop();
        let ret = await baseService.post("/channel/addChannelInfo", { pid: id, title, level: items.length - 1 });
      },
      async del(items) {
        items.pop();
        if (items.length === 0) {
          const index = state.list.indexOf(items);
          state.list.splice(index, 1);
        }
      },
      addItem() {
        state.list.push([{ title: "" }]);
      }
    };

    const state = reactive({
      list: [[{ title: "" }]]
    });

    if (props.modelValue.length > 0) {
      state.list = Object.assign({}, props.modelValue);
    }

    return {
      ...toRefs(state),
      ...methods
    };
  }
});
</script>
<style lang="scss" scoped>
.category-list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  flex: 1;
  .category-item {
    display: flex;
    flex-direction: row;
    width: 100%;
    margin-bottom: 20px;
    margin-right: 20px;
  }
  .category-item-col1 {
    flex: 1;
    max-width: 28%;
  }
  .category-item-col2 {
    flex: 1;
    max-width: 28%;
  }
  .category-item-col3 {
    flex: 1;
    max-width: 28%;
  }
  &__add {
    width: 40px;
    text-align: center;
  }
}
</style>
